package demo.thread;

public class Demo4 {
    public static int count = 0;
    public static final Object o1 = new Object();
    public static final Object o2 = new Object();
    public static void main1(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                synchronized (o1) {
                    count++;
                }
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                synchronized (o1) {
                    count++;
                }
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(count);
    }

    public static void main2(String[] args) {
        Thread t1 = new Thread(() -> {
            synchronized (o1){
                System.out.println("t1 对 o1 加锁成功");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                synchronized (o2){
                    System.out.println("t1 对 o2 加锁成功");
                }
            }
        });
        Thread t2 = new Thread(() -> {
            synchronized (o2){
                System.out.println("t2 对 o2 加锁成功");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                synchronized (o1){
                    System.out.println("t2 对 o1 加锁成功");
                }
            }
        });
        t1.start();
        t2.start();
    }
    public static void main3(String[] args) {
        synchronized (o1){
            synchronized (o2){
                System.out.println("加锁成功");
            }
        }
    }
}
